var ajaxUrlBase = location.origin + "/";
var urlBase = ajaxUrlBase;
var CODEOK = 200;
var CODEERR = 505;
/*page*/
var PageUrl = {};
/*request url*/
var ReqUrl = {};
/*取消事件的默认行为(兼容IE)*/
var stopDefault = function (ev) {
    var e = ev || window.event;
    if (e && e.preventDefault) {
        e.preventDefault();	//W3C
    } else {
        window.event.returnValue = false; //IE
    }
};
/*阻止事件冒泡(兼容IE)*/
var stopPropagation = function (ev) {
    var e = ev || window.event;
    if (e.stopPropagation) { //W3C
        e.stopPropagation();
    } else {
        e.cancelBubble = true; //IE
    }
};
/* 事件 */
function EventFun(){
    //注册
    this.add = function(elem, event, func){
        if(event === undefined){return;}
        if(elem.addEventListener){
            elem.addEventListener(event, func, false);
        } else if(elem.attachEvent){
            elem.attachEvent('on'+event, func);
        } else{
            elem['on'+event] = func;
        }
    };
    //注销
    this.remove = function(elem, event, func){
        if(event === undefined){return;}
        if(elem.removeEventListener){
            elem.removeEventListener(event, func, false);
        } else if(elem.detachEvent){
            elem.detachEvent('on'+event, func);
        } else{
            elem['on'+event] = null;
        }
    }
}
//事件
var eventFun = new EventFun();

// get request para
function GetRequest(){
    var url = decodeURI(location.search);
    var query = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            var data = strs[i].split("=");
            if(data.length == 2){
                query[data[0]] = data[1];
            }else{
                query[data[0]] = "";
            }
        }
    }
    return query;
}
// get url hash
function GetHashVal(){
    var hash = decodeURI(location.hash);
    var val = (hash || "").replace(/^\#/,'');
    return val;
}
//文本框高度自适应
function textareaAutoH(elem) {
    elem.style.height = 'auto';
    elem.scrollTop = 0;
    elem.style.height = elem.scrollHeight + 'px';
}
/*********** 提交 动画\提示语 **********/
// 加载显示
function loadAnimShow(msg){
    var msgStr = (typeof(msg) != "undefined") ? msg : '加载中...';
    layer.msg(msgStr, {icon: 16, shade: 0.3, time: 0});
}
// 加载关闭
function loadAnimHide(){
    layer.closeAll();
}
//显示
function ajaxAnimShow(msg){
    loadAnimShow(msg)
}
//关闭
function ajaxAnimHide(){
    loadAnimHide()
}
//显示加载动画
function loadingShow(){
    var $loadElem = $("#loading");
    $loadElem.stop().show();
}
//隐藏加载动画
function loadingHide(){
    var $loadElem = $("#loading");
    $loadElem.stop().fadeOut(200);
}
/**********  校验 **********/
//提示框显示信息
function tipShow(elem, msgStr){
    tipHide();
    layer.tips(msgStr, elem, {tips: [1, '#78BA32']});
}
//提示框关闭
function tipHide(){
    $(".jq_tips_box").hide().remove();
    layer.closeAll('tips');
}
/****  校验函数 ****/

//校验是否为空
function EmptyCheckMsg(value, msg){
    var res = true;
    if(value == ''){
        layer.msg(msg, {icon: 2, time: 1000});
        res = false;
    } else{
        layer.closeAll();
    }
    return res;
}
//密码校验
function PasswordCheckMsg(value){
    var res = true;
    if (value == "") {
        layer.msg("密码不能为空", {icon: 2, time: 1000});
        res = false;
    } else if (value.length < 6) {
        layer.msg("密码长度不能小于6位", {icon: 2, time: 1000});
        res = false;
    } else {
        layer.closeAll();
    }
    return res;
}

//校验是否为空
function EmptyCheck(elem, value, msg){
    var res = true;
    if(value == ''){
        tipShow(elem, msg);
        res = false;
    } else{
        tipHide();
    }
    return res;
}
//密码校验
function PasswordCheck($elem, value){
    var res = true;
    if (value == "") {
        tipShow($elem, "密码不能为空");
        res = false;
    } else if (value.length < 6) {
        tipShow($elem, "密码长度不能小于6位");
        res = false;
    } else {
        $elem.val(jQuery.trim(value));
        tipHide();
    }
    return res;
}
// 校验电话号码
function checkPhoneNumber(inVal){
    var myreg = /^[1][3,4,5,6,7,8][0-9]{9}$/;
    return myreg.test(inVal);
}
/* 字符串去除空格 */
function trim(str, dir){
    var defdir = "lr";
    do{
        if(typeof (str) !== "string"){
            break;
        }
        if (typeof (dir) !== "undefined") {
            defdir = dir;
        }
        switch(defdir){
            case "lr":  //去除左右空格
                str = str.replace(/(^\s*)|(\s*$)/g, "");
                break;
            case "l":   //去除左空格
                str = str.replace(/(^\s*)/g, "");
                break;
            case "r":   //去除右空格
                str = str.replace(/(\s*$)/g, "");
                break;
        }
    }while(0);
    return str;
}
/*** 时间信息：年、月、日、星期 ***/
function DateInfo(time) {
    var addZero = function (val) {
        var value = (parseInt(val) < 10) ? ("0" + val) : val;
        return value;
    };
    time = (typeof (time) == 'string') ? time.replace(/-/g,'/') : time;
    var date = ((typeof (time) != 'undefined' && time)) ? new Date(time) : new Date();
    return {
        year: date.getFullYear(),
        month: addZero(date.getMonth() + 1),
        day: addZero(date.getDate()),
        week: date.getDay(),
        hour: addZero(date.getHours()),
        minute: addZero(date.getMinutes()),
        second: addZero(date.getSeconds()),
        ms: date.getMilliseconds()
    };
}
//格式化时间
function fatDate(time, options){
    var setting = {
        mode: 0, // 0->日，1->月，2->年
        join: "-"
    };
    if (options === undefined){options = {};}
    if (typeof(options) === "object") {
        for(var para in options){
            setting[para] = options[para];
        }
    }
    var timeDate = (typeof (time) != 'undefined') ? DateInfo(time) : DateInfo();
    var joinStr = setting.join;
    var modeVal = parseInt(setting.mode);
    var timeTxt = "";
    var timeVal = "";
    switch(modeVal){
        case 2: //年
            timeTxt = timeDate.year+"年";
            timeVal = timeDate.year;
            break;
        case 1: //月
            timeTxt = timeDate.year+"年"+timeDate.month+"月";
            timeVal = timeDate.year+joinStr+timeDate.month;
            break;
        default: //日
            timeTxt = timeDate.year+"年"+timeDate.month+"月"+timeDate.day+"日";
            timeVal = timeDate.year+joinStr+timeDate.month+joinStr+timeDate.day;
    }
    return {
        txt: String(timeTxt),
        val: String(timeVal)
    };
}
/*** 对象操作 ***/
function ObjectFun(){
    /* flag：true -> 默认深度合并 */
    this.extend = function(defObj, inObj, flag){
        var curFlag = ((typeof(flag) != "undefined") && !flag) ? false : true;
        for(var para in inObj){
            var curObj = inObj[para];
            if((Object.prototype.toString.call(curObj) === '[object Object]') && curFlag){
                this.extend(defObj[para], curObj, curFlag);
            }
            else{
                defObj[para] = curObj;
            }
        }
        return defObj;
    };
    /* 对象拷贝 */
    this.deepcopy = function(obj, copy){
        var res = copy || {};
        for( var para in obj ){
            if( typeof obj[para] === 'object' ){
                res[para] = ( obj[para].constructor === Array ) ? [] : {};
                this.deepcopy(obj[para], res[para]);
            }else{
                res[para] = obj[para];
            }
        }
        return res;
    };
}
var objectFun = new ObjectFun();

/******** 数组操作 *********/
//数组元素下标
function indexOfArray(arr, val){
    if(!Array.indexOf){
        Array.prototype.indexOf = function(el){
            var index  = -1;
            for (var i=0,n=this.length; i<n; i++){
                if (this[i] === el){
                    index = i;
                    break;
                }
            }
            return index;
        }
    }
    return arr.indexOf(val);
}
// 检查元素是都在该数组
function isInArray(arr, val){
    return (indexOfArray(arr, val) != -1) ? true : false;
}
//判断是否为数组类型
function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]';
}
//判断是否为对象
function isObject(obj){
    return Object.prototype.toString.call(obj) === '[object Object]';
}
// 排序对象数组->按字段
function sortObjArrData(objArr, field, order){
    var prop =  (typeof(field) != "undefined") ? field : "sort";
    var isOrder =  (typeof(order) != "undefined") ? order : true; // 默认为顺序
    var compare = function(prop){
        return function(objA, objB){
            var res = 0;
            var valA = parseInt(objA[prop]);
            var valB = parseInt(objB[prop]);
            if(valA < valB){
                res = isOrder ? -1 : 1;
            }else if(valA > valB){
                res = isOrder ? 1 : -1;
            }
            return res;
        }
    };
    return objArr.sort(compare(prop));
}
//获取file文件的url
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) {
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) {
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) {
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}
// 获取图片原始尺寸
function getImgElemSize (imgElem, callback) {
    var natureSize = {};
    if(imgElem.naturalWidth) {
        natureSize.src = imgElem.src;
        natureSize.width = imgElem.naturalWidth;
        natureSize.height = imgElem.naturalHeight;
        if(typeof(callback) != "undefined"){
            callback(natureSize);
        }
    } else {
        var nImg = new Image();
        nImg.src = imgElem.src;
        if(nImg.complete){
            natureSize.src = nImg.src;
            natureSize.width = nImg.width;
            natureSize.height = nImg.height;
            if(typeof(callback) != "undefined"){
                callback(natureSize);
            }
        }else{
            nImg.onload = function() {
                natureSize.src = nImg.src;
                natureSize.width = nImg.width;
                natureSize.height = nImg.height;
                if(typeof(callback) != "undefined"){
                    callback(natureSize);
                }
            }
        }
    }
    return natureSize;
}
// 获取图片真实宽高值
function getImgSrcWH(imgSrc, callback) {
    var nImg = new Image();
    nImg.src = imgSrc;
    // 如果图片被缓存，则直接返回缓存数据
    if(nImg.complete){
        if(typeof(callback) != "undefined"){
            callback(nImg.width, nImg.height);
        }
    }else{
        // 加载完毕的事件
        nImg.onload = function() {
            if(typeof(callback) != "undefined"){
                callback(nImg.width, nImg.height);
            }
        }
    }
}

/********************** layer弹窗 ************************/

function layerPopShow(options){
    var layerOpt = {
        type: 1, anim: 2,
        title: ['', "padding-left:70px;font-size:16px;text-align:center;color:#FFF;background:#34BAB3;"],
        skin: 'demo-class',
        area: ['420px', 'auto'], //宽高
        shadeClose: false, //开启遮罩关闭
        btn: ['确定', '取消'],
        yes: function(){layer.close("page");},
        btn2: function(){layer.closeAll();},
        btnAlign: 'c',
        content: $("#popDiv")
    };
    if (typeof(options) === 'undefined'){options = {};}
    if (typeof(options) === "object") {
        for(var para in options){
            var curVal = options[para];
            if(isArray(curVal)){
                for(var i=0,size=curVal.length; i<size; i++){
                    layerOpt[para][i] = curVal[i];
                }
            }
            else{
                layerOpt[para] = curVal;
            }
        }
    }
    //弹窗
    layer.open(layerOpt);
}

/******** 功能函数 *******/

/*popwin*/
function popwinShow(flag){
    var $popwin = $("#popwin");
    if(flag){
        $popwin.stop().show();
    }else{
        $popwin.stop().fadeOut();
    }
}

// 时间处理函数
function DateFun(){
    var addZero = function (val) {
        var value = (parseInt(val) < 10) ? ("0" + val) : val;
        return value;
    };
    this.info = function (time){
        time = (typeof (time) == 'string') ? time.replace(/-/g,'/') : time;
        var date = ((typeof (time) != 'undefined' && time)) ? new Date(time) : new Date();
        return {
            year: date.getFullYear(),
            month: addZero(date.getMonth() + 1),
            day: addZero(date.getDate()),
            week: date.getDay(),
            hour: addZero(date.getHours()),
            minute: addZero(date.getMinutes()),
            second: addZero(date.getSeconds()),
            ms: date.getMilliseconds()
        };
    };
    this.fat = function(time, options){
        // yyyymmdd->年月日，yyyymm->年月，yyyy->年,
        // yyyymmddhhmmss->年月日 时分秒, yyyymmddhhmm->年月日 时分, yyyymmddhh->年月日 时
        var setting = {
            mode: "yyyymmdd",
            join: "-"
        };
        if (options === undefined) { options = {}; }
        if (typeof (options) === "object") {
            for (var para in options) {
                setting[para] = options[para];
            }
        }
        var timeDate = this.info(time);
        var joinStr = setting.join;
        var modeVal = setting.mode;
        var timeTxt = "";
        var timeVal = "";
        switch (modeVal) {
            case "yyyy":
                timeTxt = timeDate.year + "年";
                timeVal = timeDate.year;
                break;
            case "yyyymm":
                timeTxt = timeDate.year + "年" + timeDate.month + "月";
                timeVal = timeDate.year + joinStr + timeDate.month;
                break;
            case "yyyymmddhhmmss":
                timeTxt = timeDate.year + "年" + timeDate.month + "月" + timeDate.day + "日" + timeDate.hour + "时" + timeDate.minute + "分" + timeDate.second + "秒";
                timeVal = timeDate.year + joinStr + timeDate.month + joinStr + timeDate.day + " " + timeDate.hour + ":" + timeDate.minute + ":" + timeDate.second;
                break;
            case "yyyymmddhhmm":
                timeTxt = timeDate.year + "年" + timeDate.month + "月" + timeDate.day + "日" + timeDate.hour + "时" + timeDate.minute + "分";
                timeVal = timeDate.year + joinStr + timeDate.month + joinStr + timeDate.day + " " + timeDate.hour + ":" + timeDate.minute;
                break;
            case "yyyymmddhh":
                timeTxt = timeDate.year + "年" + timeDate.month + "月" + timeDate.day + "日" + timeDate.hour + "时";
                timeVal = timeDate.year + joinStr + timeDate.month + joinStr + timeDate.day + " " + timeDate.hour;
                break;
            case "yyyymmdd":
            default:
                timeTxt = timeDate.year + "年" + timeDate.month + "月" + timeDate.day + "日";
                timeVal = timeDate.year + joinStr + timeDate.month + joinStr + timeDate.day;
        }
        return {
            txt: String(timeTxt),
            val: String(timeVal)
        };
    }
}
var TimeFun = new DateFun();

/****************** bootstrap table 函数 ******************/

function BSTableFun(options){
    var setting = {
        bstElem: "#id",
        bstUseFilt: true,
        bstFiltShow: false,
        bstFiltKey: "title",
        bstOpt: {
            method: 'get',
            url: "",
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            dataType : 'json',
            queryParams: "",  //参数
            classes: 'table table-hover tableStyle',
            sortName: "",
            sortOrder: 'desc',
            striped: true,
            pagination: true,
            pageSize: 10,
            pageList: [10, 25, 50, 100, 200],
            search: false,
            showToggle : false,
            singleSelect : false,
            sidePagination: 'server',    //设置为服务器端请求
            showColumns: false,     //设置为True可显示表格显示/隐藏列表
            showRefresh: false,     //设置为True可显示刷新按钮
            minimumCountColumns: 2, //表格显示/隐藏列表时可设置最小隐藏的列数
            clickToSelect: false,   //设置为True时点击行即可选中单选/复选框
            smartDisplay:true,      //设置为True智能显示分页或者Card View
            responseHandler: "",    //在加载数据前，可以对返回的数据进行处理，参数包含：res: 返回的数据。
            columns: []
        }
    };
    if (options === undefined){options = {};}
    if (typeof(options) === "object") {
        setting = objectFun.extend(setting, options);
    }
    // 显示表格
    var $tableElem = $(setting.bstElem);
    $tableElem.bootstrapTable('destroy');
    $tableElem.bootstrapTable(setting.bstOpt);
}

/* 页面初始化 */
$(document).ready(function(){
    // 底部版权年份
    if(document.getElementById("ftCopyYear")){
        document.getElementById("ftCopyYear").innerHTML = (new Date()).getFullYear();
    }
});